package com.ksd.modules.note.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ksd.common.enums.DeletedEnums;
import com.ksd.common.enums.StatusEnums;
import com.ksd.common.po.BatchIdsPO;
import com.ksd.common.web.threadlocal.SystemIdThrealLocal;
import com.ksd.commons.BaseServiceImpl;
import com.ksd.modules.note.entity.AdminNote;
import com.ksd.modules.note.mapper.AdminNoteMapper;
import com.ksd.modules.note.po.AdminNoteSavePO;
import com.ksd.modules.note.po.AdminNoteSearchPO;
import com.ksd.modules.note.service.IAdminNoteChapterService;
import com.ksd.modules.note.service.IAdminNoteLessonService;
import com.ksd.modules.note.service.IAdminNoteService;
import com.ksd.modules.note.vo.AdminNoteVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class AdminNoteServiceImpl extends BaseServiceImpl<AdminNoteMapper, AdminNote> implements IAdminNoteService {

    @Autowired
    private IAdminNoteChapterService adminNoteChapterService;
    @Autowired
    private IAdminNoteLessonService adminNoteLessonService;


    /**
     * 查询列表
     * @param adminNoteSearchPO
     * @return
     */
    public Page<AdminNoteVo> findAdminNotes(AdminNoteSearchPO adminNoteSearchPO){
        Page<AdminNote> page = new Page<>(adminNoteSearchPO.getPageNo(),adminNoteSearchPO.getPageSize());
        LambdaQueryWrapper<AdminNote> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(AdminNote.class, c -> !c.getColumn().equalsIgnoreCase("content"));
        lambdaQueryWrapper.eq(AdminNote::getIsDeleted, DeletedEnums.UN_DELETED.getCode());
        lambdaQueryWrapper.eq(AdminNote::getSystemId,SystemIdThrealLocal.get().getSystemId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getStatus()), AdminNote::getStatus,adminNoteSearchPO.getStatus());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getSpecialFlag()), AdminNote::getSpecialFlag,adminNoteSearchPO.getSpecialFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getNotetype()), AdminNote::getNotetype,adminNoteSearchPO.getNotetype());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getNewFlag()), AdminNote::getNewFlag,adminNoteSearchPO.getNewFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getHotFlag()), AdminNote::getHotFlag,adminNoteSearchPO.getHotFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getPushFlag()), AdminNote::getPushFlag,adminNoteSearchPO.getPushFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getCategoryPid()), AdminNote::getCategoryPid,adminNoteSearchPO.getCategoryPid());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getCategoryId()), AdminNote::getCategoryId,adminNoteSearchPO.getCategoryId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getCommentFlag()), AdminNote::getCommentFlag,adminNoteSearchPO.getCommentFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getMode()), AdminNote::getMode,adminNoteSearchPO.getMode());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getVipFlag()), AdminNote::getVipFlag,adminNoteSearchPO.getVipFlag());
        // 模糊匹配
        if(StringUtils.isNotEmpty(adminNoteSearchPO.getKeyword())){
            lambdaQueryWrapper.and(c -> c.like(
                            AdminNote::getTitle,adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getNickname, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getUuid, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getTags, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getCategoryPname, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getCategoryName, adminNoteSearchPO.getKeyword())

            );
        }

        lambdaQueryWrapper.orderByDesc(AdminNote::getCreateTime);
        Page<AdminNote> adminNotePage = this.page(page, lambdaQueryWrapper);
        Page<AdminNoteVo> adminNoteVoPage = tranferPageBo(adminNotePage, AdminNoteVo.class);
        return adminNoteVoPage;
    }

    /**
     * 回收站
     * @param adminNoteSearchPO
     * @return
     */
    public Page<AdminNoteVo> findAdminNotesRecyle(AdminNoteSearchPO adminNoteSearchPO){
        Page<AdminNote> page = new Page<>(adminNoteSearchPO.getPageNo(),adminNoteSearchPO.getPageSize());
        LambdaQueryWrapper<AdminNote> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(AdminNote.class, c -> !c.getColumn().equalsIgnoreCase("content"));
        lambdaQueryWrapper.eq(AdminNote::getIsDeleted, DeletedEnums.DELETED.getCode());
        lambdaQueryWrapper.eq(AdminNote::getSystemId,SystemIdThrealLocal.get().getSystemId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getStatus()), AdminNote::getStatus,adminNoteSearchPO.getStatus());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getSpecialFlag()), AdminNote::getSpecialFlag,adminNoteSearchPO.getSpecialFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getNotetype()), AdminNote::getNotetype,adminNoteSearchPO.getNotetype());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getNewFlag()), AdminNote::getNewFlag,adminNoteSearchPO.getNewFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getHotFlag()), AdminNote::getHotFlag,adminNoteSearchPO.getHotFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getPushFlag()), AdminNote::getPushFlag,adminNoteSearchPO.getPushFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getCategoryPid()), AdminNote::getCategoryPid,adminNoteSearchPO.getCategoryPid());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getCategoryId()), AdminNote::getCategoryId,adminNoteSearchPO.getCategoryId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getCommentFlag()), AdminNote::getCommentFlag,adminNoteSearchPO.getCommentFlag());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getMode()), AdminNote::getMode,adminNoteSearchPO.getMode());
        lambdaQueryWrapper.eq(Objects.nonNull(adminNoteSearchPO.getVipFlag()), AdminNote::getVipFlag,adminNoteSearchPO.getVipFlag());
        // 模糊匹配
        if(StringUtils.isNotEmpty(adminNoteSearchPO.getKeyword())){
            lambdaQueryWrapper.and(c -> c.like(
                            AdminNote::getTitle,adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getNickname, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getUuid, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getTags, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getCategoryPname, adminNoteSearchPO.getKeyword())
                    .or().like(AdminNote::getCategoryName, adminNoteSearchPO.getKeyword())

            );
        }

        lambdaQueryWrapper.orderByDesc(AdminNote::getCreateTime);
        Page<AdminNote> adminNotePage = this.page(page, lambdaQueryWrapper);
        Page<AdminNoteVo> adminNoteVoPage = tranferPageBo(adminNotePage, AdminNoteVo.class);
        return adminNoteVoPage;
    }

    /**
     * 保存和更新
     * @param adminNoteSavePO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public AdminNoteVo saveUpdateAdminNote(AdminNoteSavePO adminNoteSavePO){
        AdminNote adminNote = tranferBo(adminNoteSavePO, AdminNote.class);
        adminNote.setSystemId(SystemIdThrealLocal.get().getSystemId());
        adminNote.setSystemName(SystemIdThrealLocal.get().getSystemName());
        boolean b = this.saveOrUpdate(adminNote);
        AdminNoteVo adminNoteVo = tranferBo(adminNote, AdminNoteVo.class);
        return adminNoteVo;
    }

    /**
     * 根据ID获取明细
     * @param id
     * @return
     */
    public AdminNoteVo getAdminNoteById(Long id){
        AdminNote adminNote = this.getById(id);
        AdminNoteVo adminNoteVo = tranferBo(adminNote, AdminNoteVo.class);
        return adminNoteVo;
    }

    /**
     * 单个逻辑删除
     * @param id
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean deleteAdminNoteById(Long id){
        boolean b =  this.updateStatus(id, AdminNote.Columns.IS_DELETED,1);
        return b;
    }

    /**
     * 单个恢复
     * @param id
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean recoverByIdAdminNote(Long id){
        boolean b =  this.updateStatus(id, AdminNote.Columns.IS_DELETED,0);
        return b;
    }

    /**
     * 单个物理删除
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean removeAdminNoteById(Long id){
        boolean b = this.removeById(id);
        if(b){
            adminNoteChapterService.removeByNoteId(id);
            adminNoteLessonService.removeByNoteId(id);
        }
        return b;
    }

    /**
     * 批量逻辑删除
     * @param batchIdsPO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean bacthDeletesAdminNote(BatchIdsPO batchIdsPO){
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }
        // 把文章分类进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminNote> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", DeletedEnums.DELETED.getCode());
        updateWrapper.in("id", ids);
        boolean b = this.update(updateWrapper);
        return true;
    }

    /**
     * 批量恢复
     * @param batchIdsPO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean batchRecoversAdminNote(BatchIdsPO batchIdsPO){
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }
        // 把文章分类进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminNote> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", DeletedEnums.UN_DELETED.getCode());
        updateWrapper.in("id", ids);
        boolean b = this.update(updateWrapper);
        return b;
    }

    /**
     * 批量物理删除
     * @param batchIdsPO
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    public Boolean batchRemovesAdminNote(BatchIdsPO batchIdsPO){
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }
        // 把文章分类进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if(b){
            adminNoteChapterService.removeByNoteIds(ids);
            adminNoteLessonService.removeByNoteIds(ids);
        }
        return b;
    }


    /**
     * 修改状态
     * @param id
     * @param column
     * @param value
     * @return
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean updateStatus(Long id,String column,Integer value){
        boolean b = super.updateStatus(id,column,value);
        return b;
    }

    /**
     * 修改状态
     * @param id
     * @param column
     * @param value
     * @return
     */
    @Override
    public boolean updateStatusStr(Long id,String column,String value){
        boolean b = super.updateStatusStr(id,column,value);
        return b;
    }

    /**
     * 批量上架
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean batchDowns(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminNote> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", StatusEnums.UN_STATUS.getCode());
        updateWrapper.in("id", ids);
        return this.update(updateWrapper);
    }

    /**
     * 批量上架
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean batchUps(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminNote> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", StatusEnums.STATUS.getCode());
        updateWrapper.in("id", ids);
        return this.update(updateWrapper);
    }

    /**
     * 复制
     * @param opid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyData(Long opid){
        AdminNote data = this.getById(opid);
        if(Objects.nonNull(data)){
            data.setId(null);
            data.setStatus(0);
            data.setCreateTime(LocalDateTime.now());
            data.setUpdateTime(LocalDateTime.now());
            data.setTitle(data.getTitle()+"[副本]");
            this.save(data);
        }
        return true;
    }
}
